package de.projectgoodmorning.bluetooth;

import java.io.InputStream;
import java.nio.channels.ClosedByInterruptException;

import javax.microedition.io.StreamConnection;

import de.projectgoodmorning.util.ArgsValidator;

public class ProcessThread extends Thread {

	private StreamConnection mConnection;
	private Processable mProcessable;

	public ProcessThread( StreamConnection connection, Processable processable ) {
		ArgsValidator.isNotNull( connection, "connection" );
		ArgsValidator.isNotNull( processable, "processable" );
		
		mConnection = connection;
		mProcessable = processable;
	}

	public void run() {
		try {
			// prepare to receive data
			InputStream inputStream = mConnection.openInputStream();

			System.out.println( "waiting for input" );
			
			while( true ) {
				byte[] buf = new byte[1024];
				inputStream.read( buf );
				
				if( isDisconntected( buf ) ) {
					throw new ClosedByInterruptException();
				}
				
				mProcessable.process( buf );
			}
		} catch( ClosedByInterruptException e ) {
			System.out.println( "Connection closed" );
		} catch( Exception e ) {
			e.printStackTrace();
		}
	}
	
	private boolean isDisconntected( byte[] buffer ) {
		for( byte b : buffer ) {
			if( b != 0 )
				return false;
		}
		
		return true;
	}
}